<template>
  <div class="order-list-page">
    <!-- 顶部标题和搜索 -->
    <van-nav-bar
      title="订单管理"
      fixed
      placeholder
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    >
      <template #right>
        <van-icon name="search" size="18" />
      </template>
    </van-nav-bar>

    <!-- 筛选区域 -->
    <div class="filters-section">
      <!-- 状态筛选 -->
      <div class="status-filter">
        <van-tabs v-model:active="activeStatusTab" shrink swipeable>
          <van-tab
            v-for="(status, index) in statusOptions"
            :title="status.label"
            :name="status.value"
            :key="index"
          />
        </van-tabs>
      </div>

      <!-- 时间筛选 -->
      <div class="time-filter">
        <van-dropdown-menu class="dropdown-menu">
          <van-dropdown-item v-model="selectedTimeFilter" :options="timeOptions" />
        </van-dropdown-menu>
        <van-calendar v-model:show="showCalendar" @confirm="onConfirmDate" />
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="list-container">
      <div class="order-header">
        <span>共 {{ filteredOrders.length }} 个订单</span>
        <van-button size="small" plain type="primary" @click="toggleSortOrder">
          {{ sortAsc ? '最新↓' : '最早↑' }}
        </van-button>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredOrders.length === 0" class="empty-list">
        <van-empty image="search" description="没有符合条件的订单">
          <van-button round type="primary" class="reset-button" @click="resetFilters">
            重置筛选条件
          </van-button>
        </van-empty>
      </div>

      <!-- 订单列表 -->
      <van-list v-else>
        <van-swipe-cell v-for="order in filteredOrders" :key="order.id" class="order-item">
          <div class="order-content" @click="viewOrderDetail(order)">
            <!-- 订单基本信息 -->
            <div class="order-info">
              <div class="flex-header">
                <span class="order-number">订单号: {{ order.orderNumber }}</span>
                <van-tag :type="getStatusTagType(order.status)">
                  {{ getStatusText(order.status) }}
                </van-tag>
              </div>
              <div class="order-time">
                <van-icon name="clock-o" />
                <span>{{ formatDate(order.createTime) }}</span>
              </div>
              <div class="customer-info">
                <van-icon name="user-circle-o" />
                <span>{{ order.customerName }} (ID: {{ order.customerId }})</span>
              </div>
              <div class="storage-info">
                <van-icon name="shop-collect" />
                <span>冷库仓号: {{ order.storageRoom }}</span>
              </div>
            </div>

            <!-- 订单金额 -->
            <div class="order-amount">¥{{ order.totalAmount.toFixed(2) }}</div>
          </div>

          <!-- 右侧操作按钮 -->
          <template #right>
            <van-button
              square
              v-if="order.status === 'pending'"
              text="取消"
              type="danger"
              class="delete-button"
              @click="cancelOrder(order.id)"
            />
          </template>
        </van-swipe-cell>
      </van-list>
    </div>

    <!-- 底部操作按钮 -->
    <div class="fixed-footer">
      <van-button round type="primary" block class="create-button" @click="goToOrderCreate">
        创建新订单
      </van-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Dialog, Toast } from 'vant'
import dayjs from 'dayjs'
import type { Order, OrderStatus } from '../types/orderList'

export default defineComponent({
  name: 'OrderListPage',
  setup() {
    const router = useRouter()

    // 状态选择
    const activeStatusTab = ref<string>('all')
    const statusOptions = ref([
      { label: '全部', value: 'all' },
      { label: '待处理', value: 'pending' },
      { label: '处理中', value: 'processing' },
      { label: '储存中', value: 'storing' },
      { label: '检测中', value: 'testing' },
      { label: '已完成', value: 'completed' },
    ])

    // 时间筛选
    const selectedTimeFilter = ref('all')
    const showCalendar = ref(false)
    const customStartDate = ref<Date | null>(null)
    const customEndDate = ref<Date | null>(null)
    const timeOptions = [
      { text: '全部时间', value: 'all' },
      { text: '今天', value: 'today' },
      { text: '本周', value: 'week' },
      { text: '本月', value: 'month' },
      { text: '自定义', value: 'custom' },
    ]

    // 排序
    const sortAsc = ref(false)

    // 模拟订单数据
    const orders = ref<Order[]>([])

    // 过滤后的订单
    const filteredOrders = computed(() => {
      let result = [...orders.value]

      // 状态过滤
      if (activeStatusTab.value !== 'all') {
        result = result.filter((order) => order.status === activeStatusTab.value)
      }

      // 时间过滤
      if (selectedTimeFilter.value !== 'all') {
        const now = dayjs()
        result = result.filter((order) => {
          const orderDate = dayjs(order.createTime)

          switch (selectedTimeFilter.value) {
            case 'today':
              return orderDate.isSame(now, 'day')
            case 'week':
              return orderDate.isSame(now, 'week')
            case 'month':
              return orderDate.isSame(now, 'month')
            case 'custom':
              if (!customStartDate.value || !customEndDate.value) return true
              return (
                orderDate.isAfter(customStartDate.value) && orderDate.isBefore(customEndDate.value)
              )
            default:
              return true
          }
        })
      }

      // 排序
      result.sort((a, b) => {
        if (sortAsc.value) {
          return a.createTime.getTime() - b.createTime.getTime()
        } else {
          return b.createTime.getTime() - a.createTime.getTime()
        }
      })

      return result
    })

    // 获取状态文本
    const getStatusText = (status: OrderStatus): string => {
      const statusMap: Record<OrderStatus, string> = {
        pending: '待处理',
        processing: '处理中',
        storing: '储存中',
        testing: '检测中',
        completed: '已完成',
        cancelled: '已取消',
      }
      return statusMap[status] || status
    }

    // 获取状态标签类型
    const getStatusTagType = (status: OrderStatus) => {
      const typeMap: Record<OrderStatus, string> = {
        pending: 'primary',
        processing: 'warning',
        storing: 'primary',
        testing: 'warning',
        completed: 'success',
        cancelled: 'danger',
      }
      return typeMap[status] || 'default'
    }

    // 格式化日期
    const formatDate = (date: Date): string => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }

    // 查看订单详情
    const viewOrderDetail = (order: Order) => {
      router.push({ name: 'OrderDetail', query: { id: order.id } })
    }

    // 取消订单
    const cancelOrder = (orderId: string) => {
      Dialog({
        title: '取消订单',
        message: '确定要取消这个订单吗？此操作不可撤销。',
      }).then(() => {
        // 找到订单并更新状态
        const order = orders.value.find((o) => o.id === orderId)
        if (order) {
          order.status = 'cancelled'
          Toast('订单已取消')
        }
      })
    }

    // 重置筛选
    const resetFilters = () => {
      activeStatusTab.value = 'all'
      selectedTimeFilter.value = 'all'
      customStartDate.value = null
      customEndDate.value = null
    }

    // 切换排序顺序
    const toggleSortOrder = () => {
      sortAsc.value = !sortAsc.value
    }

    // 确认日期选择
    const onConfirmDate = (values: any[]) => {
      customStartDate.value = values[0]
      customEndDate.value = values[1]
      selectedTimeFilter.value = 'custom'
      showCalendar.value = false
    }
    // 跳转创建订单页面
    const goToOrderCreate = () => router.push('/order')

    // 初始化模拟数据
    const initMockData = () => {
      orders.value = [
        {
          id: '1',
          orderNumber: 'ORD20230815001',
          createTime: new Date(2023, 7, 15, 10, 30),
          totalAmount: 12000.5,
          status: 'processing',
          customerName: '张先生',
          customerId: 'CUST00234',
          storageRoom: 'C-2-101',
        },
        {
          id: '2',
          orderNumber: 'ORD20230816003',
          createTime: new Date(2023, 7, 16, 14, 20),
          totalAmount: 8500.0,
          status: 'storing',
          customerName: '生物科技有限公司',
          customerId: 'CUST00789',
          storageRoom: 'A-1-205',
        },
        {
          id: '3',
          orderNumber: 'ORD20230817012',
          createTime: new Date(2023, 7, 17, 9, 15),
          totalAmount: 23000.75,
          status: 'testing',
          customerName: '王女士',
          customerId: 'CUST00567',
          storageRoom: 'B-3-312',
        },
        {
          id: '4',
          orderNumber: 'ORD20230818005',
          createTime: new Date(2023, 7, 18, 16, 45),
          totalAmount: 15600.0,
          status: 'completed',
          customerName: '李医生',
          customerId: 'CUST00321',
          storageRoom: 'D-4-104',
        },
        {
          id: '5',
          orderNumber: 'ORD20230819009',
          createTime: new Date(2023, 7, 19, 11, 20),
          totalAmount: 9500.0,
          status: 'pending',
          customerName: '陈教授',
          customerId: 'CUST00987',
          storageRoom: 'C-2-208',
        },
        {
          id: '6',
          orderNumber: 'ORD20230820017',
          createTime: new Date(2023, 7, 20, 13, 10),
          totalAmount: 18500.0,
          status: 'storing',
          customerName: '赵先生',
          customerId: 'CUST00123',
          storageRoom: 'A-1-102',
        },
      ]
    }

    // 生命周期钩子
    onMounted(() => {
      initMockData()
    })

    return {
      activeStatusTab,
      statusOptions,
      selectedTimeFilter,
      showCalendar,
      timeOptions,
      sortAsc,
      orders,
      filteredOrders,
      goToOrderCreate,
      getStatusText,
      getStatusTagType,
      formatDate,
      viewOrderDetail,
      cancelOrder,
      resetFilters,
      toggleSortOrder,
      onConfirmDate,
    }
  },
})
</script>

<style lang="scss" scoped>
.order-list-page {
  height: 100vh;
  background: #f7f9fb;
  display: flex;
  flex-direction: column;

  .filters-section {
    background: white;
    padding: 10px 16px;
    margin-bottom: 8px;
    position: sticky;
    top: 46px; // 导航栏高度
    z-index: 99;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);

    .status-filter {
      .van-tabs {
        :deep(.van-tabs__line) {
          background: #1989fa;
        }

        :deep(.van-tab) {
          font-size: 13px;
          padding: 0 8px;
        }
      }
    }

    .time-filter {
      display: flex;
      justify-content: flex-end;
      margin-top: 8px;

      .dropdown-menu {
        width: 120px;
        background: transparent;

        :deep(.van-dropdown-menu__bar) {
          box-shadow: none;
          height: auto;
        }

        :deep(.van-dropdown-menu__title) {
          padding: 0 20px 0 8px;
          font-size: 13px;
          color: #333;

          &::after {
            border-color: #969799;
          }
        }
      }
    }
  }

  .list-container {
    flex: 1;
    overflow-y: auto;
    padding: 0 12px;

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 8px;
      font-size: 13px;
      color: #969799;
    }

    .order-item {
      margin-bottom: 10px;
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);

      .order-content {
        display: flex;
        justify-content: space-between;
        background: white;
        padding: 15px;
        cursor: pointer;

        &:active {
          background-color: #f8f9fa;
        }

        .order-info {
          flex: 1;

          .flex-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;

            .order-number {
              font-weight: bold;
              font-size: 15px;
            }
          }

          .order-time,
          .customer-info,
          .storage-info {
            display: flex;
            align-items: center;
            font-size: 13px;
            color: #666;
            margin-top: 6px;

            .van-icon {
              margin-right: 5px;
              color: #969799;
              font-size: 14px;
            }
          }
        }

        .order-amount {
          font-weight: bold;
          font-size: 16px;
          color: #ee0a24;
          min-width: 90px;
          text-align: right;
          align-self: center;
        }
      }
    }

    .delete-button {
      height: 100%;
    }

    .empty-list {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 60vh;

      .reset-button {
        margin-top: 15px;
      }
    }
  }

  .fixed-footer {
    padding: 12px 16px;
    background: white;
    border-top: 1px solid #f7f8fa;

    .create-button {
      font-size: 16px;
      font-weight: bold;
      box-shadow: 0 4px 10px rgba(25, 137, 250, 0.4);
    }
  }
}
</style>
